extends Node

signal phase_changed(phase)
signal round_started(round_number)
signal round_ended(round_number)
signal preparation_time_updated(time_left)
signal battle_ended(winner)
signal preparation_started()  # Add this for AI
signal battle_started()  # Add this for AI

enum Phase { PREPARATION, BATTLE }

@export var preparation_time: float = 30.0
@export var max_battle_time: float = 60.0

var current_phase: Phase = Phase.PREPARATION
var current_round: int = 1
var phase_timer: float = 0.0
var is_active: bool = false

@onready var game_manager = get_node("/root/Main")
@onready var unit_manager = get_node("/root/Main/Units")

func _ready():
	print("RoundManager ready")
	set_process(false)
	# Start the first round after a short delay
	await get_tree().create_timer(0.5).timeout
	start_round()

func _process(delta):
	if not is_active:
		return
		
	phase_timer -= delta
	
	if current_phase == Phase.PREPARATION:
		# Emit timer update every frame during preparation
		emit_signal("preparation_time_updated", max(0, phase_timer))
		
		# Debug output every 5 seconds
		if int(phase_timer) % 5 == 0 and int(phase_timer + delta) % 5 != 0:
			print("Preparation time remaining: ", int(phase_timer), " seconds")
		
		if phase_timer <= 0:
			start_battle_phase()
	elif current_phase == Phase.BATTLE:
		if phase_timer <= 0 or check_battle_end():
			end_battle_phase()

func start_round():
	current_phase = Phase.PREPARATION
	phase_timer = preparation_time
	is_active = true
	set_process(true)
	
	emit_signal("round_started", current_round)
	emit_signal("phase_changed", current_phase)
	emit_signal("preparation_started")  # For AI
	emit_signal("preparation_time_updated", phase_timer)  # Initial timer update
	
	print("Round ", current_round, " - Preparation Phase Started (", preparation_time, " seconds)")

func start_battle_phase():
	current_phase = Phase.BATTLE
	phase_timer = max_battle_time
	emit_signal("phase_changed", current_phase)
	emit_signal("battle_started")  # For AI
	
	var all_units = get_tree().get_nodes_in_group("units")
	for unit in all_units:
		if unit.has_method("start_combat"):
			unit.start_combat()
	
	print("Round ", current_round, " - Battle Phase Started")

func end_battle_phase():
	is_active = false
	
	var all_units = get_tree().get_nodes_in_group("units")
	for unit in all_units:
		if unit.has_method("stop_combat"):
			unit.stop_combat()
	
	var winner = determine_winner()
	emit_signal("battle_ended", winner)
	emit_signal("round_ended", current_round)
	
	if winner == "draw":
		print("Round ", current_round, " - Draw!")
	else:
		print("Round ", current_round, " - Winner: ", winner)
	
	await get_tree().create_timer(2.0).timeout
	
	current_round += 1
	start_round()

func check_battle_end() -> bool:
	var player_units = get_tree().get_nodes_in_group("player_units")
	var enemy_units = get_tree().get_nodes_in_group("enemy_units")
	
	return player_units.is_empty() or enemy_units.is_empty()

func determine_winner() -> String:
	var player_units = get_tree().get_nodes_in_group("player_units")
	var enemy_units = get_tree().get_nodes_in_group("enemy_units")
	
	if player_units.is_empty() and enemy_units.is_empty():
		return "draw"
	elif enemy_units.is_empty():
		return "player"
	elif player_units.is_empty():
		return "enemy"
	else:
		return "draw"

func get_phase_name() -> String:
	return "Preparation" if current_phase == Phase.PREPARATION else "Battle"

func skip_preparation():
	if current_phase == Phase.PREPARATION:
		phase_timer = 0.0

func _input(event):
	# Press 'R' to restart/reset the current round (for testing)
	if event is InputEventKey and event.pressed and event.keycode == KEY_R:
		print("=== Restarting round (R key pressed) ===")
		restart_current_round()
	
	# Press 'B' to skip to battle phase (for testing)
	if event is InputEventKey and event.pressed and event.keycode == KEY_B:
		if current_phase == Phase.PREPARATION:
			print("=== Skipping to battle phase (B key pressed) ===")
			phase_timer = 0.1  # Set timer to almost 0 to trigger battle

func restart_current_round():
	"""Restart the current round from preparation phase"""
	print("Restarting Round ", current_round)
	is_active = false
	set_process(false)
	
	# Reset to preparation
	await get_tree().create_timer(0.1).timeout
	start_round()

func reset_board():
	"""Reset all units to their starting positions"""
	var all_units = get_tree().get_nodes_in_group("units")
	for unit in all_units:
		if unit.has_method("reset_position"):
			unit.reset_position()